const fs = require('fs');
const ExcelJS = require('exceljs');

/** 一个创建 xlsx 文件的方法
 * @param {Array} dataList 表格的详细数据
 */
async function createXlsxFile(dataList, columns, outputName, outputPath, titleList) {
  if (!dataList || !columns) return Promise.reject('createXlsxFile 方法缺少必须参数');

  const files = fs.readdirSync(outputPath);
  const fileFilter = files.filter((item) => item === outputName);
  const fileData = [];

  if (fileFilter.length) {
    const fileWorkbook = new ExcelJS.Workbook();
    await fileWorkbook.xlsx.readFile(`${outputPath}\\${outputName}`);
    const fileWorksheet = fileWorkbook.getWorksheet('Sheet1');
    fileWorksheet.eachRow((row, num) => num !== 1 && fileData.push(row.values));
  }

  const workbook = new ExcelJS.Workbook();
  const worksheet = workbook.addWorksheet('Sheet1');
  worksheet.columns = columns;
  worksheet.addRows([titleList, ...fileData, ...dataList]);

  worksheet.views = [{ state: 'frozen', ySplit: 1 }];

  const headerRow = worksheet.getRow(1);
  headerRow.eachCell((cell) => {
    cell.font = { bold: true, color: { argb: 'FFFFFF' } };
    cell.fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: '4F81BD' } };
    cell.border = { top: { style: 'thin' }, bottom: { style: 'thin' } };
  });

  await workbook.xlsx.writeFile(`${outputPath}\\${outputName}`);
  console.log(`-- 文件创建成功，文件路径 = ${outputPath}\\${outputName}`);
}

module.exports = { createXlsxFile };
